﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace XWord
{
    /// <summary>
    /// HTTP页面请求辅助类
    /// </summary>
    public class WebResourceRequest
    {
        /// <summary>
        /// 请求该URL下的页面内容
        /// </summary>
        /// <param name="url">传入的url地址</param>
        /// <returns>返回html内容</returns>
        public static string CallUrlRequest(string url)
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
            Stream dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);
            
            string responseFromServer = reader.ReadToEnd();
            response.Close();
            reader.Close();
            return responseFromServer;
        }

        /// <summary>
        /// 下载该URL的资源到本地
        /// </summary>
        /// <param name="URL">要下载的资源的地址</param>
        /// <param name="savePath">本地要保存的路径</param>
        public static void Downloadfile(string URL, string savePath)
        {
            WebClient client = new WebClient();
            int n = URL.LastIndexOf('/');
            string URLAddress = URL.Substring(0, n);  //取得网址
            string fileName = URL.Substring(n + 1, URL.Length - n - 1);  //取得文件名
            //string Dir =Htppc Server.MapPath("./");  //下载文件存放路径

            string Path = savePath + '\\' + fileName; //下载文件存放完整路径
            client.DownloadFile(URL, Path);
        }
    }
}
